from PyQt6.QtWidgets import (
    QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QProgressBar, QListWidget, QTextEdit, QSizePolicy,
    QDialog, QMessageBox
)
from PyQt6.QtGui import QMovie, QFont, QIcon, QPainter, QColor
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal
from device_info_ui import DeviceInfoUI
import subprocess
import platform
import sys
import os

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，兼容开发环境和打包后的环境"""
    try:
        # PyInstaller创建临时文件夹，将路径存储在_MEIPASS中
        base_path = sys._MEIPASS
    except Exception:
        # 如果不是打包环境，使用当前目录
        base_path = os.path.abspath(".")
    
    return os.path.join(base_path, relative_path)

class NetworkCheckThread(QThread):
    """网络检测线程"""
    network_status_changed = pyqtSignal(bool)  # 网络状态变化信号
    
    def __init__(self):
        super().__init__()
        self.running = True
    
    def run(self):
        """执行网络检测"""
        while self.running:
            try:
                # 根据操作系统选择ping命令
                if platform.system().lower() == "windows":
                    # Windows系统
                    result = subprocess.run(
                        ["ping", "-n", "1", "127.0.0.1"], 
                        capture_output=True, 
                        text=True, 
                        timeout=3,
                        creationflags=subprocess.CREATE_NO_WINDOW
                    )
                else:
                    # Linux/Mac系统
                    result = subprocess.run(
                        ["ping", "-c", "1", "127.0.0.1"], 
                        capture_output=True, 
                        text=True, 
                        timeout=3,
                        creationflags=subprocess.CREATE_NO_WINDOW
                    )
                
                # 检查ping是否成功
                if platform.system().lower() == "windows":
                    # Windows系统：通过输出内容判断是否ping通
                    is_connected = "TTL=" in result.stdout or "时间" in result.stdout
                else:
                    # Linux/Mac系统：通过returncode判断
                    is_connected = result.returncode == 0
                
                # 发送网络状态信号
                self.network_status_changed.emit(is_connected)
                
            except Exception as e:
                # 发生异常时发送网络异常信号
                self.network_status_changed.emit(False)
            
            # 等待2秒后再次检测
            self.msleep(2000)
    
    def stop(self):
        """停止线程"""
        self.running = False
        self.wait()

class NetworkStatusLight(QLabel):
    """网络状态指示灯"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(12, 12)
        self.setStyleSheet("border-radius: 6px; border: 1px solid rgba(255,255,255,0.3);")
        self.is_connected = False
        self.is_blinking = False
        self.blink_timer = QTimer()
        self.blink_timer.timeout.connect(self.toggle_blink)
        self.update_status(False)
    
    def update_status(self, connected):
        """更新网络状态"""
        self.is_connected = connected
        if connected:
            # 网络正常 - 常亮绿色
            self.setStyleSheet("""
                QLabel {
                    background-color: #4CAF50;
                    border-radius: 6px;
                    border: 1px solid rgba(255,255,255,0.3);
                }
            """)
            self.blink_timer.stop()
            self.is_blinking = False
        else:
            # 网络异常 - 开始闪烁
            if not self.is_blinking:
                self.blink_timer.start(500)  # 每500ms闪烁一次
                self.is_blinking = True
    
    def toggle_blink(self):
        """切换闪烁状态"""
        if self.is_blinking:
            current_style = self.styleSheet()
            if "background-color: #FF5722" in current_style:
                # 切换到暗色
                self.setStyleSheet("""
                    QLabel {
                        background-color: #2a2a2a;
                        border-radius: 6px;
                        border: 1px solid rgba(255,255,255,0.3);
                    }
                """)
            else:
                # 切换到亮色（红色）
                self.setStyleSheet("""
                    QLabel {
                        background-color: #FF5722;
                        border-radius: 6px;
                        border: 1px solid rgba(255,255,255,0.3);
                    }
                """)

class SearchDeviceUI(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Zero Tools")
        self.setWindowIcon(QIcon(get_resource_path("res/logo.png")))
        self.setFixedSize(650, 450)
        # 使用Windows自带标题栏
        self.setWindowFlags(Qt.WindowType.Window)
        self.init_ui()
        
        # 设备状态标记
        self.device_found_flag = False
        self.network_connected = False
        
        # 网络异常计数器
        self.network_fail_count = 0
        self.counting_enabled = True  # 是否启用计数
        
        # 初始化网络检测
        self.init_network_monitor()
        
        # 模拟设备搜索 - 5秒后找到设备
        self.search_timer = QTimer()
        self.search_timer.setSingleShot(True)  # 设置为一次性定时器
        self.search_timer.timeout.connect(self.device_found)
        self.search_timer.start(5000)  # 5000毫秒 = 5秒

    def init_network_monitor(self):
        """初始化网络监控"""
        # 创建网络检测线程
        self.network_thread = NetworkCheckThread()
        self.network_thread.network_status_changed.connect(self.on_network_status_changed)
        self.network_thread.start()

    def on_network_status_changed(self, is_connected):
        """网络状态变化处理"""
        self.network_connected = is_connected
        if is_connected:
            self.network_light.update_status(True)
            self.network_status_label.setText("网络正常")
            # 网络正常，重置失败计数
            self.network_fail_count = 0
        else:
            self.network_light.update_status(False)
            self.network_status_label.setText("网络异常")
            
            # 只有在计数启用时才增加计数
            if self.counting_enabled:
                self.network_fail_count += 1
                
                # 连续五次失败，弹窗确认退出
                if self.network_fail_count >= 5:
                    self.show_network_error_dialog()
        
        # 检查按钮状态
        self.check_button_state()

    def check_button_state(self):
        """检查并更新按钮状态"""
        # 只有当网络连接正常且设备已找到时，按钮才可用
        if self.network_connected and self.device_found_flag:
            self.enter_btn.setEnabled(True)
            # 更新按钮文字
            self.enter_btn.setText("进入设备")
        else:
            self.enter_btn.setEnabled(False)
            # 根据状态显示不同文字
            if not self.network_connected:
                self.enter_btn.setText("等待网络")
            elif not self.device_found_flag:
                self.enter_btn.setText("搜索设备中")
            else:
                self.enter_btn.setText("进入设备")

    def init_ui(self):
        # 创建主容器
        main_widget = QWidget()
        main_widget.setObjectName("mainWidget")
        main_layout = QVBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 设置主布局
        self.setLayout(QVBoxLayout(self))
        self.layout().addWidget(main_widget)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.setStyleSheet("""
            SearchDeviceUI {
                background: transparent;
            }
            QWidget#mainWidget {
                background: #173B77;
            }
        """)



        # 顶部区域 - 包含帮助按钮
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(20, 10, 20, 0)
        
        # 左侧空白
        top_layout.addStretch()
        
        # 帮助按钮 - 右上角
        help_btn = QPushButton("帮助")
        help_btn.setFixedSize(60, 30)
        help_btn.clicked.connect(self.show_help_dialog)
        help_btn.setStyleSheet("""
            QPushButton {
                background: transparent;
                color: #cfd8ff;
                border: 1px solid rgba(207, 216, 255, 0.3);
                border-radius: 15px;
                font-size: 14px;
                outline: none;
            }
            QPushButton:hover {
                background: rgba(207, 216, 255, 0.1);
                border-color: rgba(207, 216, 255, 0.5);
            }
            QPushButton:pressed {
                background: rgba(207, 216, 255, 0.3);
                border-color: rgba(207, 216, 255, 0.8);
                transform: translateY(2px);
                transition: all 0.1s ease;
            }
        """)
        top_layout.addWidget(help_btn)
        
        main_layout.addLayout(top_layout)

        card = QWidget()
        card.setObjectName("card")
        card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        card_layout = QVBoxLayout(card)
        card_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        card_layout.setSpacing(18)
        card_layout.setContentsMargins(12, 12, 12, 12)

        title = QLabel("连接您的设备")
        title.setFont(QFont("微软雅黑", 36, QFont.Weight.Bold))
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title.setStyleSheet("color: white; font-size: 48px; font-weight: bold; background: transparent;")
        card_layout.addWidget(title)

        tip = QLabel("确保您的设备开机且已插入本机，我们将自动搜索可用设备\n若mini系列无法连接，请点击帮助")
        tip.setAlignment(Qt.AlignmentFlag.AlignCenter)
        tip.setStyleSheet("color: #cfd8ff; font-size: 15px; background: transparent;")
        card_layout.addWidget(tip)

        # 搜索区域
        search_widget = QWidget()
        search_widget.setStyleSheet("background: transparent;")
        search_layout = QVBoxLayout(search_widget)
        search_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        search_layout.setSpacing(8)

        # 动图
        self.gif_label = QLabel()
        self.gif_label.setFixedSize(80, 80)
        self.gif_label.setScaledContents(True)
        self.gif_label.setStyleSheet("background: transparent;")
        self.movie = QMovie(get_resource_path("res/search.gif"))
        self.gif_label.setMovie(self.movie)
        self.gif_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.movie.start()
        search_layout.addWidget(self.gif_label, alignment=Qt.AlignmentFlag.AlignCenter)
        self.movie.setScaledSize(self.gif_label.size())
        self._last_gif_label_size = self.gif_label.size()

        # 正在搜索文字
        searching_label = QLabel("正在搜索设备…")
        searching_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        searching_label.setStyleSheet("font-size: 16px; color: #e0e6f6; background: transparent;")
        search_layout.addWidget(searching_label)

        # 进度条
        progress = QProgressBar()
        progress.setRange(0, 0)  # 不确定进度
        progress.setFixedHeight(10)
        progress.setTextVisible(False)
        progress.setStyleSheet("""
            QProgressBar {
                border-radius: 5px;
                background: #3a466b;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0, 
                    stop:0 #1e88e5, 
                    stop:0.3 #42a5f5, 
                    stop:0.7 #64b5f6, 
                    stop:1 #90caf9);
                border-radius: 5px;
            }
        """)
        search_layout.addWidget(progress)

        # 进入按钮
        self.enter_btn = QPushButton("进入设备")
        self.enter_btn.setFixedSize(120, 40)
        self.enter_btn.setEnabled(False)  # 初始状态禁用
        self.enter_btn.clicked.connect(self.show_device_info_ui)
        self.enter_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e88e5, stop:1 #1976d2);
                color: white;
                border: none;
                border-radius: 20px;
                font-size: 16px;
                font-weight: bold;
                outline: none;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #42a5f5, stop:1 #1e88e5);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1565c0, stop:1 #1976d2);
                transform: translateY(2px);
                transition: all 0.1s ease;
            }
            QPushButton:disabled {
                background: #666666;
                color: #999999;
            }
        """)
        search_layout.addWidget(self.enter_btn, alignment=Qt.AlignmentFlag.AlignCenter)

        card_layout.addWidget(search_widget)

        main_layout.addWidget(card)

        # 底部区域 - 网络状态指示和版本号
        bottom_layout = QHBoxLayout()
        bottom_layout.setContentsMargins(20, 0, 20, 10)
        
        # 网络状态指示器
        network_widget = QWidget()
        network_widget.setStyleSheet("background: transparent;")
        network_layout = QHBoxLayout(network_widget)
        network_layout.setContentsMargins(0, 0, 0, 0)
        network_layout.setSpacing(8)
        
        # 网络状态灯
        self.network_light = NetworkStatusLight()
        network_layout.addWidget(self.network_light)
        
        # 网络状态文字
        self.network_status_label = QLabel("检测中...")
        self.network_status_label.setStyleSheet("""
            QLabel {
                color: #cfd8ff;
                font-size: 12px;
                background: transparent;
            }
        """)
        network_layout.addWidget(self.network_status_label)
        
        bottom_layout.addWidget(network_widget)
        bottom_layout.addStretch()  # 中间空白
        
        # 版本号
        version_label = QLabel("v1.0.0")
        version_label.setStyleSheet("""
            QLabel {
                color: #cfd8ff;
                font-size: 12px;
                background: transparent;
                opacity: 0.7;
            }
        """)
        bottom_layout.addWidget(version_label)
        
        main_layout.addLayout(bottom_layout)

    def show_help_dialog(self):
        """显示帮助对话框"""
        help_text = """<h3>设备连接帮助</h3>
<p><b>连接步骤：</b></p>
<ol>
<li>确保设备已开机</li>
<li>使用USB线连接设备到电脑</li>
<li>等待软件自动搜索设备</li>
<li>搜索完成后点击"进入设备"按钮</li>
</ol>

<p><b>常见问题：</b></p>
<ul>
<li>如果设备无法连接，请检查USB线是否正常</li>
<li>确保设备驱动已正确安装</li>
<li>尝试重新插拔USB线</li>
<li>重启设备和电脑</li>
</ul>

<p><b>支持设备：</b></p>
<ul>
<li>Mini系列无人机</li>
<li>其他兼容设备</li>
</ul>"""
        
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle("帮助")
        msg_box.setTextFormat(Qt.TextFormat.RichText)
        msg_box.setText(help_text)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Ok)
        msg_box.setStyleSheet("""
            QMessageBox {
                background-color: #173B77;
                color: white;
            }
            QMessageBox QLabel {
                color: white;
                background: transparent;
            }
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e88e5, stop:1 #1976d2);
                color: white;
                border: none;
                border-radius: 10px;
                padding: 8px 16px;
                font-size: 14px;
                outline: none;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #42a5f5, stop:1 #1e88e5);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1565c0, stop:1 #1976d2);
                transform: translateY(1px);
            }
        """)
        msg_box.exec()

    def show_network_error_dialog(self):
        """显示网络错误弹窗"""
        # 弹窗时停止计数
        self.counting_enabled = False
        
        error_text = """<h3>网络连接异常</h3>
<p>检测到网络连接异常，连续5次网络检测失败。</p>

<p><b>可能的原因：</b></p>
<ul>
<li>网络连接已断开</li>
<li>防火墙阻止了网络连接</li>
<li>系统网络服务异常</li>
<li>网络适配器故障</li>
<li>目标设备不可达</li>
</ul>

<p><b>建议操作：</b></p>
<ol>
<li>检查网络连接是否正常</li>
<li>确认目标设备是否在线</li>
<li>重启网络适配器</li>
<li>检查防火墙设置</li>
<li>重启电脑后重试</li>
</ol>

<p>点击"确定"退出程序，或点击"取消"继续尝试。</p>"""
        
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle("网络错误")
        msg_box.setTextFormat(Qt.TextFormat.RichText)
        msg_box.setText(error_text)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
        msg_box.setDefaultButton(QMessageBox.StandardButton.Ok)
        msg_box.setStyleSheet("""
            QMessageBox {
                background-color: #173B77;
                color: white;
            }
            QMessageBox QLabel {
                color: white;
                background: transparent;
            }
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e88e5, stop:1 #1976d2);
                color: white;
                border: none;
                border-radius: 10px;
                padding: 8px 16px;
                font-size: 14px;
                outline: none;
                min-width: 80px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #42a5f5, stop:1 #1e88e5);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1565c0, stop:1 #1976d2);
                transform: translateY(1px);
            }
        """)
        
        result = msg_box.exec()
        if result == QMessageBox.StandardButton.Ok:
            # 用户选择退出程序
            import sys
            sys.exit(0)
        else:
            # 用户选择取消，重置失败计数，继续尝试
            self.network_fail_count = 0
            self.counting_enabled = True  # 重新启用计数

    def device_found(self):
        """设备找到后的处理"""
        # 停止动图
        self.movie.stop()
        
        # 更新搜索状态文字
        for child in self.findChildren(QLabel):
            if child.text() == "正在搜索设备…":
                child.setText("设备已找到")
                child.setStyleSheet("font-size: 16px; color: #4CAF50; background: transparent;")
                break
        
        # 设置设备找到标记
        self.device_found_flag = True
        
        # 隐藏进度条
        for child in self.findChildren(QProgressBar):
            child.hide()
            break
        
        # 检查按钮状态
        self.check_button_state()

    def show_device_info_ui(self):
        # 停止网络检测线程
        if hasattr(self, 'network_thread'):
            self.network_thread.stop()
        
        self.device_info_ui = DeviceInfoUI()
        self.device_info_ui.show()
        self.close()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        # 获取 gif_label 的当前大小
        label_size = self.gif_label.size()
        # 仅在尺寸变化时同步缩放，避免重复设置
        if not hasattr(self, '_last_gif_label_size') or label_size != self._last_gif_label_size:
            self.movie.setScaledSize(label_size)
            self._last_gif_label_size = label_size


